package com.woniu.gf.pawn.comm.sentinel.exception;


import com.woniu.gf.pawn.comm.core.exception.ErrorResult;
import com.woniu.gf.pawn.comm.core.exception.PawnExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @BelongsProject: gf-pawn-comm
 * @BelongsPackage: com.woniu.gf.pawn.comm.sentinel.exception.handler
 * @Author: rofus
 * @CreateTime: 2020-10-08 22:01
 * @Description:
 */
@RestControllerAdvice
@Slf4j
public class GlobalNoUrlExceptionHandler implements ErrorController {
    private final ErrorAttributes errorAttributes;
    public GlobalNoUrlExceptionHandler(ErrorAttributes errorAttributes){
        this.errorAttributes=errorAttributes;
    }
    @Override
    public String getErrorPath() {
        return "/error";
    }
    @GetMapping("/error")
    public ResponseEntity<ErrorResult> exceptionHandler(HttpServletRequest request){
        ServletWebRequest swr = new ServletWebRequest(request);
        Map<String,Object> maps=errorAttributes.getErrorAttributes(swr,true);
        if (maps.get("status").equals(404)){
            ErrorResult re = ErrorResult.builder().code(PawnExceptionCode.SYS_URL_NOT.getCode())
                    .msg("找不到资源" + maps.get("path").toString())
                    .build();
            log.error("出现异常：code:{},message:{},class:{}",404,"找不到资源",maps.get("path").toString());
            ResponseEntity<ErrorResult> resp=new ResponseEntity<>(re, HttpStatus.NOT_FOUND);
            return resp;
        }
        ErrorResult re = ErrorResult.builder()
                .code(500)
                .msg(maps.get("path").toString())
                .build();
        log.error("出现异常：code:{},message:{}",500,maps.get("message"));
        ResponseEntity<ErrorResult> resp=new ResponseEntity<>(re, HttpStatus.INTERNAL_SERVER_ERROR);
        return resp;
    }

}
